#include "Session.h"
#include <cstring>
#include <functional>
#include <iostream>
#include "Server.h"


Session::Session(boost::asio::io_context& io_context,Server *server)
: socket_(io_context),server_(server)
{
    boost::uuids::uuid a_uuid = boost::uuids::random_generator()();
    uuid_ = boost::uuids::to_string(a_uuid);
}

Session::~Session()
{
    std::cout << "Session::~Session" << std::endl;
}

void Session::Start()
{
    memset(_data, 0, sizeof(_data));
    socket_.async_read_some(boost::asio::buffer(_data,sizeof(_data)),
        std::bind(&Session::HandleRead, this, std::placeholders::_1, std::placeholders::_2,shared_from_this()));
}


void Session::HandleRead(const boost::system::error_code &ec,
        std::size_t bytes_transferred,std::shared_ptr<Session> session)
{
    if(ec)
    {
        std::cout << "HandleRead error error value: " << ec.value() << " message: " << ec.message() << std::endl;
        return;
    }
    //服务器将收到的数据发送给客户端
    boost::asio::async_write(socket_, boost::asio::buffer(_data, bytes_transferred),
        std::bind(&Session::HandleWrite, this, std::placeholders::_1, std::placeholders::_2,shared_from_this()));
    
}

void Session::HandleWrite(const boost::system::error_code &ec,
        std::size_t bytes_transferred,std::shared_ptr<Session> session)
{
    if(ec)
    {
        std::cout << "HandleWrite error error value: " << ec.value() << " message: " << ec.message() << std::endl;
        
        return;
    }
    //服务器继续等待下一次读取
    memset(_data, 0, sizeof(_data));
    socket_.async_read_some(boost::asio::buffer(_data,sizeof(_data)),
        std::bind(&Session::HandleRead, this, std::placeholders::_1, std::placeholders::_2,shared_from_this()));
}